# 自定义中间类 （执行是否登录判断）
from django.shortcuts import redirect
from django.urls import reverse
import re


class ShopMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        path = request.path

        # 判断管理后台是否登录
        # 定义后台不登录也能访问的url
        urllist = ['/myadmin/login', '/myadmin/dologin', '/myadmin/logout', '/myadmin/verify']
        # 判断当前请求url地址是否以/myadmin开头,并且不在urllist中，才做判断
        if re.match('^/myadmin', path) and (path not in urllist):
            # 判断adminuser是否存在seeion中
            if 'adminuser' not in request.session:
                # 重定向到登录页
                return redirect(reverse("myadmin_login"))

        if re.match(r"^/web",path) and (path not in urllist):
            if 'webuser' not in request.session:
                return redirect(reverse('web_login'))

        response = self.get_response(request)

        return response